const modules = import.meta.glob('/src/views/**/*.vue')

/**
 * 获取动态路由
 * @param data 后台菜单数据
 * @returns
 */
export const getFormatDynamicRouter = async (data: any[]) => {
  return await formatDynamicRouter(data)
}

/**
 * 递归处理后台菜单数据(树型结构)
 * @param res 后台菜单数据(树型结构)
 */
const formatDynamicRouter = (res: any) => {
  const data = res.map((item: any) => {
    if (item.children.length > 0) {
      const router = formatData(item)
      router.children = formatDynamicRouter(router.children)
      return router
    } else {
      return formatData(item)
    }
  })
  return data
}

/**
 * 路由格式模板
 * @param data
 * @returns
 */
const formatData: any = (data: any) => {
  const router = {
    name: data.name,
    path: data.path,
    icon: data.icon,
    component: modules[`/src/views/${data.component}` + '.vue'],
    meta: {
      title: data.title,
      login: true,
      ...data.meat,
    },
    children: data.children,
    redirect: data.redirect,
    title: data.title,
    isShow: data.isShow,
  }

  return router
}
